﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using BLL;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxPro;
using System.Text;
using DAL;
using System.Data.SqlClient;

/// <summary>
/// Summary description for AppBLL
/// </summary>
/// public partial class
/// 

namespace Portal
{
    public partial class AppBLL : Page
    {
        private string loginName;
        private bool isLogin;

        public AppBLL()
        {
            //
            // TODO: Add constructor logic here
            //            
            if (Session["Khach"] != null) {
                isLogin = true;
                loginName = Session["Khach"].ToString();
            }            
        }

       

        [AjaxPro.AjaxMethod]
        public string BuildUrlSearch(string keyword, string siteid)
        {
            return EnvInfo.HttpRoot + siteid + "/search/" + keyword + ".html";            
        }
        [AjaxPro.AjaxMethod]
        public string ServerBuyProduct(string pid)
        {
            new Portal.AppBLL().AddItemtoCart(pid, "1");
            return DAL.EnvInfo.HttpRoot + "cart.html";
        }
    


        [AjaxPro.AjaxMethod]
        public string RenderShoppingCart(string siteid)
        {
            StringBuilder Html = new StringBuilder();
            int totalItem = 0;
            try
            {
                totalItem = GetCartIdtem().Rows.Count;
            }
            catch (Exception ex){}

            Html.Append(
                //"<div id=\"shoppingcart\">"+
                "    <a href=\"" + EnvInfo.HttpRoot + "cart.html\">MyCart (" + totalItem + " products)</a>"
                //"</div>"
                );

            return Html.ToString();
        }
        public void AddItemtoCart(string pid, string itemNumber)
        {
            DataTable selectedProducts = new CmsBLL().ReadingProductsByIdToCart(pid, itemNumber);
            if (Session["Cart"] == null)
            {
                Session["Cart"] = selectedProducts;
            }
            else
            {
                DataTable dtCart = (DataTable)Session["Cart"];
                //foreach (DataRow dr in dtCart.Rows)
                //{
                dtCart.ImportRow(selectedProducts.Rows[0]);
                //}

                Session["Cart"] = dtCart;
            }

            // return selectedProducts;
        }
        public DataTable GetCartIdtem()
        {
            DataTable dtCart = CartTable();
            if (Session["Cart"] != null)
            {
                dtCart = (DataTable)Session["Cart"];
            }

            return dtCart;
        }
        [AjaxPro.AjaxMethod]
        public string GetIdtemToCart(string siteid, string productId, string itemNo,int actionType)
        {
            string html = string.Empty;
            try
            {
                DataTable selectedProducts = new DataTable();
                if (actionType != 3)
                {
                    selectedProducts = new CmsBLL().ReadingProductsByIdToCart(productId, itemNo);
                }
                if (Session["Cart"] == null)
                {
                    Session["Cart"] = selectedProducts;
                }

                else
                {
                    DataTable dtCart = (DataTable)Session["Cart"];
                    switch (actionType)
                    {
                        case 1://add item 
                            DataRow subdr = dtCart.Rows.Find(productId);
                            if (subdr != null)
                            {
                                subdr["ItemNumber"] = Convert.ToInt16(subdr["ItemNumber"]) + 1;
                                dtCart.AcceptChanges();
                            }
                            else
                                dtCart.ImportRow(selectedProducts.Rows[0]);
                            break;
                        case 2://update item 
                            string[] arrVal = productId.Split('|');
                            for (int i = 0; i < arrVal.Length; i++)
                            {
                                string[] proItem = arrVal[i].Split(';');
                                if (proItem.Length > 1)
                                {
                                    DataRow getdr = dtCart.Rows.Find(proItem[0].Substring(("txt_").Length));
                                    if (getdr != null)
                                    {
                                        getdr["ItemNumber"] = proItem[1];
                                        dtCart.AcceptChanges();
                                    }
                                }
                                
                            }
                            html = new CmsBLL().RenderShoppingCartDetail(siteid, dtCart, isLogin, loginName);
                            break;
                        case 3://remove
                            DataRow dr = dtCart.Rows.Find(productId);
                            dtCart.Rows.Remove(dr);
                            html = new CmsBLL().RenderShoppingCartDetail(siteid, dtCart,isLogin,loginName);
                            
                            break;
                    }
                    //dtCart.ImportRow(selectedProducts.Rows[0]);
                    Session["Cart"] = dtCart;
                }
            }
            catch (Exception ex) { return "ERROR:" + ex.Message; }
            return html;
        }
        public DataTable CartTable()
        {
            DataTable dtCart = new DataTable();
            dtCart.Columns.Add(new DataColumn("ProductID", typeof(string)));
            dtCart.PrimaryKey = new DataColumn[]{ dtCart.Columns["ProductID"]};
            
            dtCart.Columns.Add(new DataColumn("ProductName", typeof(string)));
            dtCart.Columns.Add(new DataColumn("NewPrice", typeof(float)));
            dtCart.Columns.Add(new DataColumn("ItemNumber", typeof(Int32)));
            dtCart.Columns.Add(new DataColumn("CateID", typeof(float)));
            dtCart.Columns.Add(new DataColumn("BaoHanh", typeof(float)));
            return dtCart;
        }

        #region Contact
        [AjaxPro.AjaxMethod]
        public string SaveContact(string name, string email, string phone, string address, string message)
        {
            string reval = string.Empty;
            string Query = "INSERT INTO tbl_Contact(FullName,Email,Address,PhoneNumber,Title,Body,Created) " +
                        "		VALUES(@FullName,@Email,@Address,@PhoneNumber,@Title,@Body,@Created) ";

            using (SqlConnection sqlConnection = new SqlConnection(EnvInfo.ConnectionString))
            {
                try
                {
                    sqlConnection.Open();
                    SqlCommand sqlCommand = sqlConnection.CreateCommand();
                    sqlCommand.CommandText = Query;
                    sqlCommand.Parameters.Add("@FullName", SqlDbType.NVarChar, 50);
                    sqlCommand.Parameters["@FullName"].Value = name;
                    sqlCommand.Parameters.Add("@Email", SqlDbType.VarChar, 50);
                    sqlCommand.Parameters["@Email"].Value = email;
                    sqlCommand.Parameters.Add("@Address", SqlDbType.NVarChar, 100);
                    sqlCommand.Parameters["@Address"].Value = address;
                    sqlCommand.Parameters.Add("@PhoneNumber", SqlDbType.VarChar, 50);
                    sqlCommand.Parameters["@PhoneNumber"].Value = phone;
                    sqlCommand.Parameters.Add("@Title", SqlDbType.NVarChar, 200);
                    sqlCommand.Parameters["@Title"].Value = "";
                    sqlCommand.Parameters.Add("@Body", SqlDbType.NVarChar, 2000);
                    sqlCommand.Parameters["@Body"].Value = message;
                    sqlCommand.Parameters.Add("@Created", SqlDbType.DateTime);
                    sqlCommand.Parameters["@Created"].Value = DateTime.Now;

                    sqlCommand.ExecuteNonQuery();
                }
                catch (Exception ex) { reval = "ERROR: "+ex.Message; }

            }

            return reval;
        }
        #endregion
    }
}